function gradients = calculateGradients(weights, neuronOutputs, ...
                                        neuronInputs, action, ...
                                        correctOutput, lambda)

numGradients = length(weights);
gradients = cell(numGradients, 1);

delta = (neuronOutputs{end}(2 : end, action) - correctOutput) ...
            .* (1 - tanh(neuronInputs{end}(:, action)) .^ 2);

for i = numGradients : -1 : 1
    gradients{i} = delta * neuronOutputs{i}(:, action)';
    gradients{i}(:, 2 : end) = gradients{i}(:, 2 : end) + ...
                                lambda * weights{i}(:, 2 : end);

    delta = weights{i}' * delta;
    delta = delta(2 : end, :) .* (1 - tanh(neuronInputs{i}(:, action)) .^ 2);
end
